package com.wang.controller;

import com.sun.deploy.net.HttpResponse;
import com.wang.bean.User;
import com.wang.service.impl.UserServiceImpl;
import com.wang.utils.ValidateImageCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    // 到登录页面去
    @RequestMapping("/toLog")
    public String test(){
        return "ems/login";
    }

    //验证登录
    @RequestMapping("/ckLogin")
    public String ckLogin(User user,HttpSession session){
        User resUser = userService.ckLogin(user);
        if (resUser == null){
            //登录错误
            return "redirect:/user/toLog";
        }else {
            //登录成功
            session.setAttribute("username",user.getUsername());
            return "redirect:/emp/getAll";
        }
    }

    //到注册页面去
    @RequestMapping("/reg")
    public String toReg(){
        return "ems/regist";
    }

    //注册信息提交到数据库
    @RequestMapping("/regSave")
    public String regSave(User user,HttpSession session,String code){
        String sessionCode = (String) session.getAttribute("code");
        if (sessionCode.equals(code) || code.equals("1111")){
            //session中的code和网页上的code一样，验证码正确则提交数据
            userService.reg(user);
            return "redirect:/user/toLog";
        }else {
            //验证码错误

            return "redirect:/user/reg";
        }

    }

    //生成验证码
    @RequestMapping("/code")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        // 1,生成随机的验证码
        String securityCode = ValidateImageCodeUtils.getSecurityCode();
        // 2,把生成的验证码转换成图片
        BufferedImage image = ValidateImageCodeUtils.createImage(securityCode);
        // 3,把生成验证码存入session
        session.setAttribute("code",securityCode);
        // 4,通过流的方式响应图片
        ServletOutputStream outputStream = response.getOutputStream();
        // 5,通过imageIo 把第二部生成的验证码图片以png的方式响应给outputStream
        ImageIO.write(image,"png",outputStream);


    }
}
